package com.sping_boot3.spirng_boot3.juc.异步回调;

import lombok.SneakyThrows;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;

public class Demo01 {
    @SneakyThrows
    public static void main(String[] args) {
       comp01();
//        comp02();
    }

    @SneakyThrows
    private static void comp02() {
        System.out.println("线程名:"+Thread.currentThread().getName());

        CompletableFuture.supplyAsync(() -> {
            System.out.println("线程名:"+Thread.currentThread().getName());
            int nextInt = ThreadLocalRandom.current().nextInt(10);
            try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}
            return String.valueOf(nextInt);

        }).whenComplete((r,e) ->{
            if(e == null) {
                System.out.println("计算完成结果为：" + r);
            }
        }).exceptionally( throwable -> {
            System.out.println("出现异常："+throwable);
            return null;
        });
        System.out.println("线程名:"+Thread.currentThread().getName()+"：去忙去他的了");
        try {Thread.sleep(3000);} catch (InterruptedException e) {throw new RuntimeException(e);}

    }

    @SneakyThrows
    private static void comp01() {
        System.out.println("线程名:"+Thread.currentThread().getName());

        CompletableFuture<String> voidCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("线程名:"+Thread.currentThread().getName());
            try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}
            System.out.println("结果为："+3);
            return "3";
        });
        System.out.println("线程名:"+Thread.currentThread().getName()+"：去忙去他的了");
        voidCompletableFuture.whenComplete((r,e) ->{
            System.out.println("计算完成值为："+r);
        });
        try {Thread.sleep(3000);} catch (InterruptedException e) {throw new RuntimeException(e);}
    }


}
